import { useRequest } from "ahooks";
import { LoadMoreFormatReturn } from '@ahooksjs/use-request/lib/types';
import { fetchSearchCustomer } from "@/pages/index/service";
import { CustomerInfo } from "@/pages/index/type";
import { useEffect, useState } from "react";
import Taro, { useRouter } from "@tarojs/taro";

type IPageParams = {
  gender: '1' | '2',
  title: string
}

function useData() {
  // 1:男, 2：女
  const { params } = useRouter<IPageParams>()
  const [searchObj, setSearchObj] = useState<Partial<CustomerInfo>>()
  const { data: customerList } = useRequest((d) => queryCustomerList(searchObj, params, d), {
    loadMore: true,
    refreshDeps: [searchObj],
    isNoMore: (r) => !r?.hasMore
  })

  useEffect(() => {
    Taro.setNavigationBarTitle({
      title: params.title
    })
  }, [])

  return {
    customerList: customerList?.list,
    setSearchObj
  }
}

export default useData

async function queryCustomerList(options?: Partial<CustomerInfo>, params?: IPageParams, d?: LoadMoreFormatReturn) {
  const { current = 0 } = d || { current: 0 };
  const { res } = await fetchSearchCustomer({
    ...options,
    gender: params?.gender,
    size: 10,
    current,
  });

  if (res) {
    return {
      list: res.records,
      current: res.current + 1,
      hasMore: res.total > res.pages * res.size,
    };
  }
  return {
    list: [] as CustomerInfo[],
    hasMore: false,
  };
}